#include <QThread>
#include <QListWidget>
#include <QVBoxLayout>
#include <QFileInfo>
#include <QCheckBox>
#include <QKeyEvent>

#include "webparser.h"
#include "../pageimagesparser.h"

namespace Jcr
{

class WebParserPrivate
{
public:
    void deleteSelectedItems();

    QListWidget* listWidget;
    QCheckBox* selectAllCheckBox;
    QUrl url;
};

void WebParserPrivate::deleteSelectedItems()
{
    QList<QListWidgetItem*> selectedItems;
    for (int i = 0; i < listWidget->count(); ++i) {

        QListWidgetItem* selectedItem = listWidget->item(i);
        if (selectedItem->isSelected())
            selectedItems.append(selectedItem);
    }

    qDeleteAll(selectedItems);
}

WebParser::WebParser(QWidget *parent) : QWidget(parent)
{
    d_ptr = new WebParserPrivate;
    d_ptr->listWidget = new QListWidget(this);
    d_ptr->listWidget->setAlternatingRowColors(true);
    d_ptr->listWidget->setSelectionMode(QAbstractItemView::MultiSelection);

    d_ptr->selectAllCheckBox = new QCheckBox(tr("Select All"), this);

    QVBoxLayout* layout = new QVBoxLayout;
    layout->addWidget(d_ptr->listWidget);
    layout->addWidget(d_ptr->selectAllCheckBox);
    setLayout(layout);

    connect(d_ptr->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(onItemDblClicked(QListWidgetItem*)));
    connect(d_ptr->listWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onItemClicked(QListWidgetItem*)));
    connect(d_ptr->selectAllCheckBox, SIGNAL(stateChanged(int)), this, SLOT(onSelectAllChecked(int)));
}

WebParser::~WebParser()
{
    delete d_ptr;
}

void WebParser::setUrl(const QUrl& url)
{
    if (d_ptr->url != url) {
        d_ptr->url = url;

        Jcr::PageImagesParser* pip = new Jcr::PageImagesParser();
        pip->setUrl(url);

        QThread* thread = new QThread();
        pip->moveToThread(thread);

        connect(thread, SIGNAL(started()), pip, SLOT(run()));
        connect(pip, SIGNAL(finished()), thread, SLOT(terminate()));
        connect(pip, SIGNAL(finished()), thread, SLOT(deleteLater()));
        connect(pip, SIGNAL(finished()), this, SLOT(onFinishedParsing()));
        thread->start();
    }
}

QUrl WebParser::url() const
{
    return d_ptr->url;
}

void WebParser::downloadSelectedItems()
{
    for (int i = 0; i < d_ptr->listWidget->count(); ++i) {
        QListWidgetItem* item = d_ptr->listWidget->item(i);
        if (item->checkState() == Qt::Checked) {
            emit download(QUrl(item->text()));
        }
    }
}

void WebParser::keyPressEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_Delete)
        d_ptr->deleteSelectedItems();

    QWidget::keyPressEvent(e);
}

void WebParser::contextMenuEvent(QContextMenuEvent *e)
{

}

void WebParser::onFinishedParsing()
{
    Jcr::PageImagesParser* pip = qobject_cast<Jcr::PageImagesParser*>(sender());
    QList<QUrl> images = pip->images();

    d_ptr->listWidget->clear();
    foreach (auto image, images) {
        QListWidgetItem* item = new QListWidgetItem;
        item->setCheckState(Qt::Unchecked);
        item->setText(image.toString());

//        QFileInfo fi(image.toString());
//        const QString ext = fi.suffix().toLower();
//        if (ext == "gif")
//            item->setIcon(QIcon(":/images/gif.png"));
//        else if (ext == "png")
//            item->setIcon(QIcon(":/images/png.png"));
//        else if (ext == "jpg")
//            item->setIcon(QIcon(":/images/jpg.png"));

        d_ptr->listWidget->addItem(item);
    }

    pip->deleteLater();
}

void WebParser::onItemDblClicked(QListWidgetItem* item)
{
    emit download(QUrl(item->text()));
}

void WebParser::onItemClicked(QListWidgetItem *item)
{
    Q_UNUSED(item)
    bool enabled = false;
    for (int i = 0; i < d_ptr->listWidget->count(); ++i) {
        if (d_ptr->listWidget->item(i)->checkState() == Qt::Checked) {
            enabled = true;
            break;
        }
    }
    emit downloadEnabled(enabled);
}

void WebParser::onSelectAllChecked(int state)
{
    emit downloadEnabled(d_ptr->listWidget->count() > 0 && state == Qt::Checked);
    for (int i = 0; i < d_ptr->listWidget->count(); ++i)
        d_ptr->listWidget->item(i)->setCheckState((Qt::CheckState)state);
}

} // namespace jcr
